﻿using System;
using System.Diagnostics;
using System.Threading.Tasks;

namespace OJS.Worker
{           
    /// <summary>
    /// C++ Compiler
    /// </summary>
    public class CPPCompiler : ICompiler
    {
        /// <summary>
        /// Compile method
        /// </summary>
        /// <param name="source">source code string</param>
        /// <returns>Compile result</returns>
        public CompileResult Compile(string sourcePath)
        {
            CompileResult cResult = null;
            var fileName = sourcePath.Substring(0, sourcePath.LastIndexOf("."));
            var startInfo = new ProcessStartInfo 
            {
                FileName = "g++",
                Arguments = string.Format(" -o {0} {1}", fileName, sourcePath)
            };

            var compiler = new Process
            {
                StartInfo = startInfo,
                EnableRaisingEvents = true,                
            };                       

            compiler.Exited += (s, e) =>
            {            
                if (compiler.ExitCode == 0) cResult = new CompileResult(true, fileName + ".exe");                
                else cResult = new CompileResult(false, error: compiler.StandardError.ReadToEnd());
            };

            compiler.Start();
            while (!compiler.HasExited) System.Threading.Thread.Sleep(200);

            return cResult;
        }
    }
}
